package com.qunarmei.niotest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.concurrent.Executors;


/**
 *
 *  NIO  客户端  没有解决沾包问题
 */
public class NIOClient {

    public static void main(String[] args) throws Exception{
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置非阻塞
        socketChannel.configureBlocking(false);

        Selector selector = Selector.open();

        socketChannel.register(selector,SelectionKey.OP_CONNECT);

        //提供服务器端的IP和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //连接服务器
        socketChannel.connect(inetSocketAddress);

        while (true){

            selector.select();
            Set<SelectionKey> selectionKeys =  selector.selectedKeys();
            for (SelectionKey selectionKey : selectionKeys) {

                if(selectionKey.isConnectable()){

                    SocketChannel client = (SocketChannel) selectionKey.channel();

                    if(client.isConnectionPending()){

                        client.finishConnect();

                        //如果连接成功，发送数据
                        String str="客户端连接成功";
                        //直接将字符串对应的字节数组包裹到buffer中,不用指定大小
                        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());


                        //发送数据，将buffer写入到channel
                        client.write(buffer);


                        Executors.newSingleThreadExecutor().execute(()->{

                            while (true){

                                try {
                                    buffer.clear();
                                    InputStreamReader reader = new InputStreamReader(System.in);
                                    BufferedReader bufferedReader = new BufferedReader(reader);

                                    String sendmessage = bufferedReader.readLine();
                                    buffer.put(sendmessage.getBytes());
                                    buffer.flip();
                                    client.write(buffer);


                                }catch (Exception e){

                                }

                            }

                        });
                        client.register(selector,SelectionKey.OP_READ);
                    }

                }else if(selectionKey.isReadable()){

                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    ByteBuffer readbuffer =ByteBuffer.allocate(2048);
                    int count =  client.read(readbuffer);
                    if(count>0){

                        String receivedmessage =new String(readbuffer.array(),0,count);
                        System.out.println(receivedmessage);

                    }



                }

            }


        }

    }
}